import Vue from 'vue'
import VueRouter from 'vue-router'
// 安装使用路由
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',   //history模式，不显示#
  routes: [
    {
      name: 'default',
      path: '/',
      redirect: { name: 'index' },
    },
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/login.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'register',
      path: '/register',
      component: () => import('@/views/register.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'personal',
      path: '/personal/:id',
      component: () => import('@/views/personal.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'editPersonal',
      path: '/editPersonal/:id',
      component: () => import('@/views/editPersonal.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'index',
      path: '/index',
      component: () => import('@/views/index.vue'),
      meta: { keepAlive: true }
    },
    {
      name: 'articleDetail',
      path: '/articleDetail/:id',
      component: () => import('@/views/articleDetail.vue'),
      meta: { keepAlive: false }    // 不需要缓存
    },
    {
      name: 'myfollows',
      path: '/myfollows',
      component: () => import('@/views/myfollows.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'mystars',
      path: '/mystars',
      component: () => import('@/views/mystars.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'comment',
      path: '/comment/:id',
      component: () => import('@/views/comment.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'categoryManager',
      path: '/categoryManager',
      component: () => import('@/views/categoryManager.vue'),
      meta: { keepAlive: false }
    },
    {
      name: 'search',
      path: '/search',
      component: () => import('@/views/search.vue'),
      meta: { keepAlive: false }
    }
  ]
})


// 添加全局导航前置守卫
router.beforeEach((to, from, next) => {
  // console.log(to.path);
  let arr = ['/personal'];
  // 判断用户当前目标路由是否需要守卫功能
  arr.forEach(item => {
    if (to.path.indexOf(item) != -1) {
      let token = localStorage.getItem('hmtoutiao_token');
      if (token) {
        next();
      } else {
        next({ name: 'login' })
      }
    } else {
      next()
    }
  })
  // if (arr.indexOf(to.path) != -1) {
  //   let token = localStorage.getItem('hmtoutiao_token');
  //   if (token) {
  //     next();
  //   } else {
  //     next({ name: 'login' })
  //   }
  // } else {
  //   next()
  // }
})


export default router